package com.xm.xmapp.myreceiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.xm.xmapp.ActivityListDetailsActivity;
import com.xm.xmapp.BigCustomerActivity;
import com.xm.xmapp.CompanyUserActivity;
import com.xm.xmapp.DialogActivity;
import com.xm.xmapp.MainActivity;
import com.xm.xmapp.MessageDetailsActivity;
import com.xm.xmapp.MyAssetDetailsActivity;
import com.xm.xmapp.StartActivity;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.Type;
import com.xm.xmapp.response.bean.JpushNotifactionResponse;
import com.xm.xmapp.response.bean.JpushReceiverResponse;
import com.xm.xmapp.response.bean.ResponseUserBean;
import com.xm.xmapp.service.MusicService;

public class JpushReceiver extends BroadcastReceiver {
	private boolean isGetData = true;
	private static final String TAG = "JPush";

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			JpushReceiverResponse bean = JSON.parseObject(bundle.getString(JPushInterface.EXTRA_EXTRA),
					JpushReceiverResponse.class);
			switch (bean.type) {
			case JpushReceiverResponse.SHORT_TIME_NO_FROM_ORDER:
			case JpushReceiverResponse.SHORT_TIME_NO_FROM_SUB:
			case JpushReceiverResponse.SHORT_TIME_ORDER:
			case JpushReceiverResponse.SHORT_TIME_SUBSCRIBE:
			case JpushReceiverResponse.SHORT_TIME_SEND:

				if (isGetData) {
					isGetData = false;
					MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.JPUSH_CODE, bean);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							isGetData = true;
						}
					}, CodeConstant.pushTime);
				}
				break;
			// 用户被公司邀请加入
			// 用户被公司退出拿车大客户
			case JpushReceiverResponse.BIGCUSTOMER_IN:
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.JPUSH_CODE, bean);
				MyAppcation.getMyAppcation().notifyDataSetChanged(CompanyUserActivity.class,
						Type.A_CompanyUser.JPUSH_IN, bean);
				break;
			case JpushReceiverResponse.BIGCUSTOMER_OUT:
				ResponseUserBean userBean = MyAppcation.getMyAppcation().getUserBean();
				if (userBean != null) {
					userBean.is_big_customer_user = 0;
					MyAppcation.getMyAppcation().saveUserBean(userBean);
				}
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.JPUSH_CODE, bean);
				MyAppcation.getMyAppcation().notifyDataSetChanged(BigCustomerActivity.class,
						Type.A_BigCustomer.JPUSH_OUT, bean);

				break;
			// 大客户订单刷新
			case JpushReceiverResponse.BIGCUSTOMER_SUBSCRIBE:
			case JpushReceiverResponse.BIGCUSTOMER_ORDER:
			case JpushReceiverResponse.BIGCUSTOMER_NO_FROM_ORDER:
			case JpushReceiverResponse.BIGCUSTOMER_NO_FROM_SUB:
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.JPUSH_CODE, bean);
				break;
			case JpushReceiverResponse.PILE:// 充电桩订单数据刷新
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainActivity.class, Type.A_Main.JPUSH_CODE, bean);
				break;

			default:
				break;
			}

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
			// Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			String json = bundle.getString(JPushInterface.EXTRA_EXTRA);
			final JpushNotifactionResponse bean = JSON.parseObject(json, JpushNotifactionResponse.class);
			if (bean != null && bean.messageType == 4) {
				long lastServiceTime = bean.pushServiceTime * 1000 + 10 * 60 * 1000;// 服务器返回加十分钟
				if (System.currentTimeMillis() <= lastServiceTime) {

					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							JpushNotifactionResponse.Voice voice = JSON.parseObject(bean.data,
									JpushNotifactionResponse.Voice.class);
							Intent intentSV = new Intent(MyAppcation.getMyAppcation(), MusicService.class);
							intentSV.putExtra("type", voice.voice);
							MyAppcation.getMyAppcation().startService(intentSV);
						}
					}, 1000);
				}
			} else {
				if (bean.messageId != 0) {
					if (bean.messageType == 5) {
						if (MyAppcation.getMyAppcation().getTopActivity() != null) {
							Intent myIntent = new Intent(context, DialogActivity.class);
							myIntent.putExtra("bean", bean);
							myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							context.startActivity(myIntent);
						}
					}
				}
			}

		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			// Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
			String json = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JpushNotifactionResponse bean = JSON.parseObject(json, JpushNotifactionResponse.class);
			// ｛type=’message’, messageId = 消息id ， messageType =
			// 1=系统消息，2=活动消息，3=个人消息｝
			if (bean.messageId != 0) {
				switch (bean.type) {
				case "message":
					Intent myIntent;
					switch (bean.messageType) {
					case 1:
						myIntent = new Intent(context, MessageDetailsActivity.class);
						myIntent.putExtra("id", bean.messageId + "");
						myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(myIntent);
						break;
					case 2:
						myIntent = new Intent(context, ActivityListDetailsActivity.class);
						myIntent.putExtra("id", bean.messageId + "");
						myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(myIntent);
						break;
					case 3:
						myIntent = new Intent(context, MyAssetDetailsActivity.class);
						myIntent.putExtra("id", bean.messageId + "");
						myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(myIntent);
						break;
					case 5:
						if (MyAppcation.getMyAppcation().getTopActivity() != null) {
							myIntent = new Intent(context, DialogActivity.class);
							myIntent.putExtra("bean", bean);
							myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							context.startActivity(myIntent);
						} else {
							myIntent = new Intent(context, StartActivity.class);
							myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							myIntent.putExtra("bean", bean);
							context.startActivity(myIntent);
						}
						break;

					default:
						break;
					}
					break;

				default:
					break;
				}
			} else {
				if (bean.messageType == 4 && !isForeground(context)) {
					Intent myIntent = new Intent(context, StartActivity.class);
					myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(myIntent);
				}

			}

		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
			// 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
			// 打开一个网页等..

		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
			boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
		} else {
			Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
		}
	}

	// 当前应用是否处于前台
	private boolean isForeground(Context context) {
		if (context != null) {
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
			String currentPackageName = cn.getPackageName();
			if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
				return true;
			}
			return false;
		}
		return false;
	}

	public static void startActivityForPackage(Context context, String packName) {
		Intent intent = context.getPackageManager().getLaunchIntentForPackage(packName);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
}
